package com.act;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.UserInfo;
import com.common.Constant;
import com.control.UserControl;
import com.fragment.MineFragment;
import com.xike.kyt.R;
import com.mUI.MyProgressDialog;
import com.mUI.MyUploadingDialog;
import com.xike.util.Manager;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class LoginUserInfo extends BaseAct implements OnClickListener {

	private static final int REQUEST_CODE_PHOTO_GRAPH = 1;
	private static final int REQUEST_CODE_PHOTO_ZOOM = 2;
	private static final int REQUEST_CODE_PHOTO_RESOULT = 3;

	private static final int REQUEST_CODE_TO_UPDATE_INFO = 4;
	private static final int REQUEST_CODE_TO_LOGIN = 5;
	private static final int REQUEST_CODE_TO_BIND_MOBILE = 6;

	private static final String IMAGE_UNSPECIFIED = "image/*";

	private File file;
	private Bitmap bitmap_up;// 存放图片

	String strUserName;
	Bitmap bpUserAvator;
	String strUserAvator;
	TextView tv_userName;
	String newNickName = "";
	private ImageView img_avator;
	private Bitmap defalutBitmap;

	boolean userInfoIsChange = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login_userinfo);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.containsKey("userNickName")) {
			strUserName = bundle.getString("userNickName");
		}

		if (bundle != null && bundle.containsKey("userAvatorBitmap")) {
			bpUserAvator = (Bitmap) bundle.get("userAvatorBitmap");
		} else if (bundle != null && bundle.containsKey("userAvator")) {
			strUserAvator = bundle.getString("userAvator");
		}

		BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
		defalutBitmap = MyUtil.getRoundedCornerBitmap(bd.getBitmap());
		initViews();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_UPDATE_INFO && resultCode > 0) {
			newNickName = data.getExtras().getString("nickName");
			if (StringUtil.isNotNull(newNickName)) {
				tv_userName.setText(newNickName);
				userInfoIsChange = true;
			}
		} else if (requestCode == REQUEST_CODE_PHOTO_GRAPH) {// 拍照
			startPhotoZoom(Uri.fromFile(file));
		} else if (requestCode == REQUEST_CODE_TO_BIND_MOBILE && resultCode > 0) {
			// serviceGetUserInfo(userId);
			// 跳转到拨打电话
			// Intent it_call = new Intent
		}

		if (data == null)
			return;

		if (requestCode == REQUEST_CODE_PHOTO_ZOOM) {
			startPhotoZoom(data.getData());
		}
		if (requestCode == REQUEST_CODE_PHOTO_RESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				bitmap_up = extras.getParcelable("data");
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap_up.compress(Bitmap.CompressFormat.JPEG, 75, stream);
				serviceUploadAvator();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void initViews() {
		findViewById(R.id.headTitle_tv_back).setOnClickListener(this);
		findViewById(R.id.loginUserInfo_layout_head).setOnClickListener(this);
		findViewById(R.id.loginUserInfo_layout_name).setOnClickListener(this);

		img_avator = (ImageView) findViewById(R.id.loginUserInfo_img_head);
		tv_userName = (TextView) findViewById(R.id.loginUserInfo_tv_name);
		MyUtil.setTextViewText(tv_userName, strUserName, 0, "");
		if (bpUserAvator != null && bpUserAvator.getWidth() > 0) {
			img_avator.setImageBitmap(MyUtil.getRoundedCornerBitmap(bpUserAvator));
		} else {
			MyUtil.displayImageView(this, strUserAvator, img_avator, defalutBitmap, true);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.headTitle_tv_back:
			finishAcitity();
			break;
		case R.id.loginUserInfo_layout_name:
			intentToUpdateUserInfoAct();
			break;
		case R.id.loginUserInfo_layout_head:
			final MyUploadingDialog mDialog = new MyUploadingDialog(LoginUserInfo.this);
			mDialog.setCanceledOnTouchOutside(true);
			mDialog.show();
			WindowManager windowManager = getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes();
			lp.width = (int) (display.getWidth()); // 设置宽度
			mDialog.getWindow().setAttributes(lp);
			mDialog.setOnBtnPhotoClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_PICK, null);
					intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
					startActivityForResult(intent, REQUEST_CODE_PHOTO_ZOOM);
					mDialog.dismiss();
				}
			});
			mDialog.setOnBtnTakePic(new OnClickListener() {

				@Override
				public void onClick(View v) {
					getPhoto();
					mDialog.dismiss();
				}
			});

			break;

		default:
			break;
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			finishAcitity();
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	private void finishAcitity() {
		if (userInfoIsChange) {
			Intent it_back = new Intent(this, MineFragment.class);
			if (StringUtil.isNotNull(newNickName)) {
				it_back.putExtra("newNickName", newNickName);
			}

			if (bitmap_up != null && bitmap_up.getWidth() > 0) {
				it_back.putExtra("newAvator", bitmap_up);
			}

			setResult(1, it_back);
		}
		finish();
	}

	@Override
	protected void updateViews() {
	}

	private void serviceUploadAvator() {
		MyProgressDialog.show(this, true);
		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SERVICEDATA_ERROR:
					MyProgressDialog.cancle();
					mToast.showToast(LoginUserInfo.this, getString(R.string.net_error));
					break;
				case MSG_SERVICEDATA_OK:
					MyProgressDialog.cancle();
					BaseBean result = (BaseBean) msg.obj;
					if (result.isResult()) {
						mToast.showToast(LoginUserInfo.this, "上传成功");
						img_avator.setImageBitmap(bitmap_up);
						userInfoIsChange = true;
					} else {
						mToast.showToast(LoginUserInfo.this, result.getError_description());
					}
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}

		};
		Manager.singleThread.execute(new Runnable() {

			@Override
			public void run() {
				ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("access_token", UserControl.getAccessToken()));
				params.add(new BasicNameValuePair("app_key", Constant.APPKEY));
				params.add(new BasicNameValuePair("client_info", Manager.getClientInfo()));
				String strSignature = StringUtil.MD5(Constant.APPSERRET + UserControl.getAccessTokenSecret());
				params.add(new BasicNameValuePair("signature", strSignature));

				params.add(new BasicNameValuePair("sign", MyUtil.getSignRequestParams(params)));

				String strResult = client.postBitmapContent(Constant.SERVER_URL_USER_AVATOR, bitmap_up, "avator", params);
				BaseBean result = gson.fromJson(strResult, BaseBean.class);
				Message msg = new Message();
				msg.what = MSG_SERVICEDATA_ERROR;
				if (result != null) {
					msg.what = MSG_SERVICEDATA_OK;
					msg.obj = result;
				}
				handler.sendMessage(msg);

			}
		});

	}

	private void intentToUpdateUserInfoAct() {
		Intent it_updateUserInfo = new Intent(this, UpdateUserInfoAct.class);
		it_updateUserInfo.putExtra("nickName", tv_userName.getText().toString());
		startActivityForResult(it_updateUserInfo, REQUEST_CODE_TO_UPDATE_INFO);

	}

	/**
	 * 拍照上传
	 * 
	 * @param uri
	 */
	private void getPhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String path = Environment.getExternalStorageDirectory().toString();
		File f = new File(path);
		if (null != f)
			if (null == f.listFiles()) {
				mToast.showToast(LoginUserInfo.this, "未检测到SD卡");
				return;
			}
		for (File fileDel : f.listFiles()) {// /
											// 删除遗留的相片保证用户sd卡只有一张temp图
			if (null != fileDel)
				if (fileDel.toString().endsWith("_temp.jpg")) {
					fileDel.delete();
				}
		}
		file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + "_temp.jpg");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, REQUEST_CODE_PHOTO_GRAPH);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_PHOTO_RESOULT);
	}
}
